import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/pay_model/query_rechange_rrices_model.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/investmoney/investmoney_controller.dart';
import 'package:yysk_app/pages/show_image/show_image_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/checkbox_widget.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';

class InvestmoneyPage extends GetView<InvestmoneyController> {
  static const path = '/investmoneyPage';
  const InvestmoneyPage({super.key});

  @override
  Widget build(BuildContext context) {
    final double top = MediaQuery.of(context).padding.top;

    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: AppColors.backgroundColorBlack,
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: ImageAssetWidget(
              width: 375.px,
              height: 812.px,
              imageUrl: 'static/images/bg.png',
            ),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(0, top, 0, 24.px),
            child: Column(
              children: [
                CustomAppBar2(title: '充值', context: context),
                Expanded(
                  child: Obx(
                    () => Padding(
                      padding: EdgeInsets.symmetric(
                        horizontal: 16.px,
                        vertical: 0,
                      ),
                      child: ListView(
                        padding: EdgeInsets.zero,
                        children: [
                          hiSpace(height: 20.px),
                          Container(
                            padding: EdgeInsets.fromLTRB(
                              16.px,
                              18.px,
                              16.px,
                              16.px,
                            ),
                            decoration: BoxDecoration(
                              color: AppColors.backgroundColorBlackLight,
                              borderRadius: BorderRadius.circular(10.px),
                              border: Border.all(
                                width: 1.px,
                                color: Color.fromRGBO(255, 255, 255, 0.1),
                              ),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  '充值金额',
                                  style: TextStyle(
                                    fontSize: 12.px,
                                    fontWeight: FontWeight.bold,
                                    color: AppColors.fontColorSearchEE,
                                  ),
                                ),
                                Row(
                                  children: [
                                    Expanded(
                                      child: TextField(
                                        controller: controller.amountController,
                                        keyboardType:
                                            TextInputType.numberWithOptions(
                                              decimal: true,
                                            ),
                                        style: TextStyle(
                                          fontSize: 24.px,
                                          color: AppColors.fontColorSearchEE,
                                        ),
                                        decoration: const InputDecoration(
                                          border: InputBorder.none,
                                          hintText: '输入金额',
                                        ),
                                        onChanged: (value) {
                                          if (controller.choosePrice.value !=
                                              value) {
                                            controller.choosePrice.value = '';
                                          }
                                          // if (value != '' &&
                                          //     (value.compareTo(
                                          //           controller
                                          //               .rechangePricesDetail
                                          //               .value!
                                          //               .rechargePrice!
                                          //               .balance!,
                                          //         ) <=
                                          //         0)) {
                                          //   controller.timer?.cancel();
                                          //   if (isLastCharDot(value)) return;
                                          // } else {
                                          //   if (value == '' ||
                                          //       isLastCharDot(value)) {
                                          //   } else {
                                          //     showToast('请输入合理的提现金额');
                                          //   }
                                          // }
                                        },
                                        inputFormatters: [
                                          FilteringTextInputFormatter(
                                            RegExp("[0-9.]"),
                                            allow: true,
                                          ),
                                          MyNumberTextInputFormatter(digit: 2),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                                Divider(color: AppColors.backgroundColorGreyF8),
                                hiSpace(height: 12.px),
                                Text(
                                  '账户余额：${controller.rechangePricesDetail.value?.rechargePrice?.balance ?? 0.00}',
                                  style: TextStyle(
                                    fontSize: 12.px,
                                    color: AppColors.fontColor,
                                  ),
                                ),
                                hiSpace(height: 36.px),
                                controller.rechangePricesDetail.value != null &&
                                        controller
                                                .rechangePricesDetail
                                                .value
                                                ?.rechargePrice !=
                                            null &&
                                        controller
                                            .rechangePricesDetail
                                            .value!
                                            .rechargePrice!
                                            .rechargePrices!
                                            .isNotEmpty
                                    ? Wrap(
                                      spacing: 8,
                                      runSpacing: 8,
                                      children: [
                                        ...?controller
                                            .rechangePricesDetail
                                            .value!
                                            .rechargePrice
                                            ?.rechargePrices!
                                            .map(
                                              (String item) =>
                                                  _buildText(item, controller),
                                            ),
                                      ],
                                    )
                                    : SizedBox(),
                              ],
                            ),
                          ),
                          SizedBox(height: 32.px),
                          Text(
                            '选择充值方式',
                            style: TextStyle(
                              fontSize: 12.px,
                              color: AppColors.fontColorSearchEE,
                            ),
                          ),
                          hiSpace(height: 10.px),
                          ...controller.payList.value!.map((e) {
                            return _payItem(
                              context: context,
                              item: e as CashierRouteData,
                              controller: controller,
                            );
                          }),
                        ],
                      ),
                    ),
                  ),
                ),
                Column(
                  children: [
                    ButtonWidget(
                      label: '确认充值',
                      height: 40.px,
                      width: 347.px,
                      fontSize: 16.px,
                      fontColor: AppColors.fontColor21,
                      onPressed: () {
                        GlobalController globaController = Get.find();
                        if (globaController.hasAuth.value == false) {
                          controller.toSm(context: context);
                          return;
                        }
                        controller.isOpenWallet();
                      },
                    ),
                    SizedBox(height: 20.px),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  bool isLastCharDot(String? str) {
    return str != null && !str.isEmpty && str.endsWith('.');
  }
}

//支付页面
_payItem({
  required BuildContext context,
  required CashierRouteData item,
  required InvestmoneyController controller,
}) {
  return GestureDetector(
    excludeFromSemantics: true,
    onTap: () {},
    child: Container(
      width: context.width,
      padding: EdgeInsets.fromLTRB(20.px, 21.px, 20.px, 21.px),
      margin: EdgeInsets.only(bottom: 10.px),
      decoration: BoxDecoration(
        color: AppColors.backgroundColorBlackLight,
        borderRadius: BorderRadius.circular(8.px),
      ),

      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          CheckboxWidget(onChanged: (value) {}, checked: true, size: 18),
          hiSpace(width: 12.px),
          Text(
            '${item.payMethodName}',
            style: TextStyle(
              fontSize: 16.px,
              color: AppColors.fontColorSearchEE,
            ),
          ),
          SizedBox(
            width: 75.px,
            child:
                item.bankTransLimitImg != null
                    ? InkWell(
                      onTap: () {
                        Get.toNamed(
                          ShowImagePage.path,
                          arguments: {
                            'title': '查看限额',
                            'url': Uri.encodeComponent(
                              '${item.bankTransLimitImg}',
                            ),
                          },
                        );
                      },
                      child: Text(
                        '查看限额 >',
                        style: TextStyle(
                          fontSize: 12.px,
                          color: AppColors.backgroundColorGrey,
                          overflow: TextOverflow.visible,
                        ),
                        textAlign: TextAlign.right,
                      ),
                    )
                    : Text(''),
          ),
        ],
      ),
    ),
  );
}

_buildText(String txt, dynamic controller) {
  return GestureDetector(
    onTap: () {
      controller.chooseTxt(txt);
    },
    child: Container(
      width: 96.px,
      height: 34.px,
      decoration: BoxDecoration(
        color: AppColors.backgroundColorGreyF8,
        borderRadius: BorderRadius.circular(6.px),
        border:
            controller.choosePrice.value == txt
                ? Border.all(width: 1.px, color: AppColors.fontColorSearch)
                : null,
      ),
      child: Center(
        child: Text(
          txt,
          style: TextStyle(
            color:
                controller.choosePrice.value == txt
                    ? AppColors.fontColorSearch
                    : AppColors.fontColor,
            fontSize: 18.px,
          ),
        ),
      ),
    ),
  );
}

class MyNumberTextInputFormatter extends TextInputFormatter {
  static const defaultDouble = 0.001;

  ///允许的小数位数，-1代表不限制位数
  int digit;
  MyNumberTextInputFormatter({this.digit = -1});
  static double strToFloat(String str, [double defaultValue = defaultDouble]) {
    try {
      return double.parse(str);
    } catch (e) {
      return defaultValue;
    }
  }

  ///获取目前的小数位数
  static int getValueDigit(String value) {
    if (value.contains(".")) {
      return value.split(".")[1].length;
    } else {
      return -1;
    }
  }

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    if (value == ".") {
      value = "0.";
      selectionIndex++;
    } else if (value == "-") {
      value = "-";
      selectionIndex++;
    } else if (value != "" &&
            value != defaultDouble.toString() &&
            strToFloat(value, defaultDouble) == defaultDouble ||
        getValueDigit(value) > digit) {
      value = oldValue.text;
      selectionIndex = oldValue.selection.end;
    }
    return new TextEditingValue(
      text: value,
      selection: new TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
